import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:clipboard/clipboard.dart';
import 'services/fcm_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FCM Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'FCM Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String? _fcmToken;
  bool _isLoading = false;
  bool _isInitializing = false;
  bool _isSubscribed = false;
  final FCMService _fcmService = FCMService();

  @override
  void initState() {
    super.initState();
    _initializeFCM();
  }

  Future<void> _initializeFCM() async {
    setState(() {
      _isInitializing = true;
    });

    try {
      final success = await _fcmService.initialize();
      if (success) {
        _showSnackBar('FCM 初始化成功');
      } else {
        _showSnackBar('FCM 初始化失败');
      }
    } catch (e) {
      _showSnackBar('FCM 初始化出错: $e');
    } finally {
      setState(() {
        _isInitializing = false;
      });
    }
  }

  Future<void> _getFCMToken() async {
    if (!_fcmService.isInitialized) {
      _showSnackBar('请先等待 FCM 初始化完成');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final token = await _fcmService.getFCMToken();
      setState(() {
        _fcmToken = token;
        _isLoading = false;
      });

      if (token != null) {
        _showSnackBar('FCM Token 获取成功');
      } else {
        _showSnackBar('获取 FCM Token 失败，请检查权限设置');
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showSnackBar('获取 FCM Token 失败: $e');
    }
  }

  Future<void> _subscribeToTopic() async {
    if (!_fcmService.isInitialized) {
      _showSnackBar('请先等待 FCM 初始化完成');
      return;
    }

    if (_fcmToken == null) {
      _showSnackBar('请先获取 FCM Token');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final success = await _fcmService.subscribeToTopic('topic-en-us-all888');
      setState(() {
        _isSubscribed = success;
        _isLoading = false;
      });

      if (success) {
        _showSnackBar('成功订阅主题: topic-en-us-all888');
      } else {
        _showSnackBar('订阅主题失败');
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showSnackBar('订阅主题出错: $e');
    }
  }

  void _copyFCMToken() {
    if (_fcmToken != null) {
      FlutterClipboard.copy(_fcmToken!);
      _showSnackBar('FCM Token 已复制到剪贴板');
    } else {
      _showSnackBar('请先获取 FCM Token');
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
    );
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'FCM 消息通知演示',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 30),

            // FCM 初始化状态
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _fcmService.isInitialized
                    ? Colors.green.withOpacity(0.1)
                    : Colors.orange.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: _fcmService.isInitialized
                      ? Colors.green
                      : Colors.orange,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    _fcmService.isInitialized
                        ? Icons.check_circle
                        : Icons.hourglass_empty,
                    color: _fcmService.isInitialized
                        ? Colors.green
                        : Colors.orange,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _isInitializing
                        ? 'FCM 初始化中...'
                        : _fcmService.isInitialized
                        ? 'FCM 已初始化'
                        : 'FCM 未初始化',
                    style: TextStyle(
                      color: _fcmService.isInitialized
                          ? Colors.green
                          : Colors.orange,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // FCM Token 显示区域
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'FCM Token:',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    _fcmToken ?? '未获取',
                    style: const TextStyle(
                      fontFamily: 'monospace',
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // 按钮区域
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed:
                          (_isLoading ||
                              _isInitializing ||
                              !_fcmService.isInitialized)
                          ? null
                          : _getFCMToken,
                      child: _isLoading
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Text('获取 FCM Token'),
                    ),
                    ElevatedButton(
                      onPressed: _fcmToken != null ? _copyFCMToken : null,
                      child: const Text('复制 Token'),
                    ),
                  ],
                ),

                const SizedBox(height: 10),

                ElevatedButton(
                  onPressed:
                      (_isLoading ||
                          _isInitializing ||
                          !_fcmService.isInitialized ||
                          _fcmToken == null)
                      ? null
                      : _subscribeToTopic,
                  child: _isLoading
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Text('订阅主题: topic-en-us-all888'),
                ),
              ],
            ),

            const SizedBox(height: 20),

            // 主题订阅状态
            if (_isSubscribed)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.green),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.check_circle, color: Colors.green),
                    SizedBox(width: 8),
                    Text(
                      '已订阅主题: topic-en-us-all888',
                      style: TextStyle(color: Colors.green),
                    ),
                  ],
                ),
              ),

            const SizedBox(height: 30),

            // 原有的计数器功能
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
